package org.stvd.controller.admin;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.admin.Resources;
import org.stvd.service.admin.GuidsService;
import org.stvd.service.admin.ResourcesService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Title ResourcesController
 * @Describtion 系统资源控制类
 * @author houzx
 * @date 2022年5月9日
 */
@Api(tags = "系统资源接口类")
@Controller
@RequestMapping("/admin/resources")
public class ResourcesController extends BaseController {

    @Autowired
    ResourcesService resourcesService;
    @Autowired
    private GuidsService guidsService;
    
    @Value("${top_guid}")
    private String topGuid = "";
    
    private String tmpURL = "/admin/resources/";

   /**
     * 系统资源请求
     * @param resources
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "management")
    public String onResourcePageLoad(@ModelAttribute("resources") Resources resources) {
        if(StringUtil.isEmpty(resources.getType())){
            resources.setType("URL");
        }
        if(!StringUtil.isEmpty(request.getParameter("gid"))) {
            resources.setGuid(request.getParameter("gid"));
        }
        if(StringUtil.isEmpty(resources.getGuid())) {
            resources.setGuid(StringUtil.isEmpty(topGuid) ? Consts.GUID : topGuid);
        }
        loadResource(resources);
        return tmpURL + "ResourcesManagement.html";
    }
    
    @ApiIgnore
    @PostMapping(value = "management")
    public String onResourcePageAction(@ModelAttribute("resources") Resources resources) {
    loadResource(resources);
    return tmpURL + "ResourcesManagement.html";
    }
    
    // 加载系统资源信息公共方法
    private void loadResource(Resources resources) {
        map.put("queryResult", resourcesService.getResourceQueryResult((pageNo - 1) * pageSize, pageSize,
            resources.getType(), resources.getGuid()));
        String userId = SecurityUserHolder.getCurrentUserId();
        map.put("guidsList", guidsService.listGuidByUserId(userId));
        map.put("guids", guidsService.findByPk(Guids.class, StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid));
    }
    
    /**
     * 资源新增
     * @param resources
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "add/{guid}")
    public String onAddLoad(@PathVariable String guid, 
        @ModelAttribute("resources") Resources resources) {
        map.put("guid", guid);
        return tmpURL + "ResourcesAdd.html";
    }

    @ApiOperation("新增资源信息")
    @Log(title = "新增资源信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onAddAction(
        @Valid @ModelAttribute("resources") Resources resources, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        resources.setResId(StringUtil.getRandomUUID());
        resourcesService.insert(resources);
        
        map.clear();
        result.setMsg("新增成功！");
        return result;

    }

    /**
     * 资源修改
     * @param resId
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "edit/{resId}")
    public String onEditLoad(@PathVariable String resId,
        @ModelAttribute("resources") Resources resources) {
        resources = resourcesService.findByPk(Resources.class, resId);
        map.put("resources", resources);
        return tmpURL + "ResourcesEdit.html";
    }

    @ApiOperation(value = "修改资源信息")
    @Log(title = "修改资源信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onEditAction(
        @Valid @ModelAttribute("resources") Resources resources, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        resourcesService.update(resources);
        map.clear();
        result.setMsg("修改成功！");
        return result;
    }

    /**
     * 资源删除
     * @param resId
     * @param resName
     * @return
     */
    @ApiOperation(value = "删除资源信息")
    @Log(title = "删除资源信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>>  onDelete(String resId, String resName) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            resourcesService.delete(Resources.class, resId);
            result.setMsg("资源‘" + resName + "’删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除资源" + resName + "失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
}
